package com.itany.corejava.code13_jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author MissChen
 * @version 1.0
 * @date 2023 年12月13日 13:34
 */
public class Test10_事务 {
    public static void main(String[] args) throws DataAccessException {
        User user=new User("xiaohua3","12345678","12345678111","南通");
        insertUser(user);
    }
    public static void insertUser(User user) throws DataAccessException {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn=JDBCUtil.getConnection();
            //开启事务
            conn.setAutoCommit(false);
            String sql=new StringBuffer()
                    .append(" insert into ")
                    .append(" t_user ")
                    .append(" (username,password,phone,address) ")
                    .append(" values ")
                    .append(" (?,?,?,?) ")
                    .toString();
            ps=conn.prepareStatement(sql);
            ps.setString(1,user.getUsername());
            ps.setString(2,user.getPassword());
            ps.setString(3,user.getPhone());
            ps.setString(4,user.getAddress());
            ps.executeUpdate();


            //业务全部结束之后，提交事务，此时只要报错，则不会提交
            conn.commit();

        } catch (DataAccessException e) {
            System.out.println("----------------------");
            try {
                conn.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
                throw  new DataAccessException("事务回滚出问题了");
            }
            throw e;
        } catch (SQLException e) {
            System.out.println("********************");
            try {
                conn.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
                throw  new DataAccessException("事务回滚出问题了");
            }
            throw new DataAccessException("数据库访问失败");
        } finally {
            JDBCUtil.close(conn,ps,null);
        }
    }
}
